package com.yuntongxun.ecdemo.voicechat.ui.activity;

import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.voicechat.api.ApiConstants;
import com.yuntongxun.ecdemo.voicechat.comman.Contants;
import com.yuntongxun.ecdemo.voicechat.presenter.ICommonRequestPresenter;
import com.yuntongxun.ecdemo.voicechat.presenter.impl.CommonRequestPresenterImpl;
import com.yuntongxun.ecdemo.voicechat.util.PreferenceUtils;
import com.yuntongxun.ecdemo.voicechat.util.http.HttpStatusUtil;
import com.yuntongxun.ecdemo.voicechat.util.iview.ICommonViewUi;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/12/28.
 */

public class ModifyPsdActivity extends BaseChatActivity implements ICommonViewUi {


    @InjectView(R.id.email_edt)
    EditText emailEdt;
    @InjectView(R.id.code_edt)
    EditText codeEdt;
    @InjectView(R.id.vercode_tv)
    TextView loginVercodeTv;
    @InjectView(R.id.get_vercode_btn)
    CardView getVercodeNext;
    @InjectView(R.id.password_edt)
    EditText passwordEdt;
    @InjectView(R.id.password_confirm_edt)
    EditText passwordConfirmEdt;
    @InjectView(R.id.next_btn)
    Button nextBtn;

    public ICommonRequestPresenter iCommonRequestPresenter;

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_forget_psd;
    }

    @Override
    protected void initViewsAndEvents() {
        setTitle("Change password");
        iCommonRequestPresenter = new CommonRequestPresenterImpl(mContext, this);

    }

    @OnClick(R.id.next_btn)
    public void onNextClick() {

        if (TextUtils.isEmpty(emailEdt.getText().toString().trim())) {
            showToastLong("Please input valid email! ");
            return;
        }

        if (!isEmail(emailEdt.getText().toString().trim())) {
            showToastLong("Please input valid email! ");
            return;
        }

        if (TextUtils.isEmpty(codeEdt.getText().toString().trim())) {
            showToastLong("Verifycode cannot be empty!");
            return;
        }

        if (TextUtils.isEmpty(passwordEdt.getText().toString().trim())) {
            showToastLong("password cannot be empty!");
            return;
        }

        if (TextUtils.isEmpty(passwordConfirmEdt.getText().toString().trim())) {
            showToastLong("Repassword cannot be empty!");
            return;
        }

        if (!passwordConfirmEdt.getText().toString().trim().endsWith(passwordEdt.getText().toString().trim())) {
            showToastLong("Inconsistent passwords!");
            return;
        }

        toRequest(ApiConstants.EventTags.FIND_PSD);
    }

    public boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    private Timer timer;
    private int second = 60;
    private void initializeSecond() {
        int oldSecond = PreferenceUtils.getPrefInt(mContext,
                Contants.Preference.register_milliser_number, 60);

        long currentTime = System.currentTimeMillis();
        long oldTime = PreferenceUtils.getPrefLong(mContext,
                Contants.Preference.register_milliser, currentTime);
        long nowTime = currentTime;

        int distance = (int) ((nowTime - oldTime) / 1000);

        second = oldSecond - distance;

        if (second <= 0 || second == 60) {
            second = 60;
        } else {
            CountDown();
        }
    }

    private void CountDown() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            // TimerTask 是个抽象类,实现的是Runable类
            @Override
            public void run() {
                second--;
                myHandler.sendEmptyMessage(second);
                Log.e("second",second+"");
            }
        }, 0, 1000);
    }

    final Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (isFinishing()) {
                return;
            }

            if (msg.what > 0) {
                getVercodeNext.setEnabled(false);
                loginVercodeTv.setText("Wait(" + msg.what + "s)");
//                getVercodeNext.setCardBackgroundColor(getResources().getColor(R.color.gray2));
            } else {
                second = 60;
                loginVercodeTv.setText("Verify Code");
//                getVercodeNext.setCardBackgroundColor(getResources().getColor(R.color.colorPrimary));
                getVercodeNext.setEnabled(true);
                if (timer != null) {
                    timer.cancel();
                }
            }
        }
    };

    @OnClick(R.id.get_vercode_btn)
    public void getVercodeClick(){
        getVercodeNext.setEnabled(false);
        toRequest(ApiConstants.EventTags.REGISTER_SMS);
    }


    @Override
    public void toRequest(int eventTag) {
        if (eventTag == ApiConstants.EventTags.REGISTER_SMS) {
            //发送验证码
            String email = emailEdt.getText().toString();

            if (!isEmail(email)){
                showToastLong("Please input valid email! ");
                getVercodeNext.setEnabled(true);
                return;
            }

            RequestParams params = new RequestParams();
            params.put("email", email);
            iCommonRequestPresenter.request(eventTag, mContext, ApiConstants.Urls.REGISTER_SMS, params);

        }else if (eventTag == ApiConstants.EventTags.FIND_PSD){
            RequestParams params = new RequestParams();
            params.put("email", emailEdt.getText().toString().trim());
            params.put("pwd", passwordEdt.getText().toString().trim());
            params.put("code", codeEdt.getText().toString().trim());
            iCommonRequestPresenter.request(eventTag, mContext, ApiConstants.Urls.FIND_PSD, params);
        }
    }

    @Override
    public void getRequestData(int eventTag, String result) {
        if (eventTag == ApiConstants.EventTags.REGISTER_SMS) {
            //发送验证码
            showToastLong(HttpStatusUtil.getStatusMsg(result));
            CountDown();
        }else if (eventTag == ApiConstants.EventTags.FIND_PSD){
            PreferenceUtils.setPrefString(this, Contants.Preference.USER_PSD,passwordEdt.getText().toString().trim());
            finish();
        }
    }

    @Override
    public void onRequestSuccessException(int eventTag, String msg) {
        showToastLong(msg);
    }

    @Override
    public void onRequestFailureException(int eventTag, String msg) {
        showToastLong(msg);
    }

    @Override
    public void isRequesting(int eventTag, boolean status) {
        if (eventTag==ApiConstants.EventTags.REGISTER_SMS){
            return;
        }
        if (status) {
            showKProgress("Waiting");
        } else {
            dimissKProgress();
            getVercodeNext.setEnabled(true);
        }
    }
}
